<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { useTodoStore } from "../stores/todo";
import { useSettingsStore } from "../stores/settings";
import ConfirmDialog from "../components/ConfirmDialog.vue";
import AutoResizeTextarea from "../components/AutoResizeTextarea.vue";
import ViewToolbar from "../components/ViewToolbar.vue";
import { useTodoDelete } from "../composables/useTodoDelete";
import dayjs from "dayjs";
import { useAutoAnimate } from "@formkit/auto-animate/vue";

const todoStore = useTodoStore();
const settingsStore = useSettingsStore();
const [todoListRef] = useAutoAnimate({ duration: 500 });

// 删除功能
const { showDeleteConfirm, deleteTodo, confirmDelete, cancelDelete } =
  useTodoDelete();

// 当前选中的日期
const selectedDate = ref(dayjs());
const editingId = ref<string | null>(null);
const editingContent = ref("");
const newTodoContent = ref("");
const hoveredId = ref<string | null>(null); // 鼠标悬停的待办 ID

// 生成一周的日期
const weekDates = computed(() => {
  const start = selectedDate.value.startOf("week");
  return Array.from({ length: 7 }, (_, i) => {
    const date = start.add(i, "day");
    return {
      date,
      dayName: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"][
        date.day()
      ],
      dateStr: date.format("MM-DD"),
      isSelected:
        date.format("YYYY-MM-DD") === selectedDate.value.format("YYYY-MM-DD"),
      isToday: date.format("YYYY-MM-DD") === dayjs().format("YYYY-MM-DD"),
    };
  });
});

// 当前日期的待办
const currentTodos = computed(() => {
  const todos = todoStore.getTodosByDate(
    selectedDate.value.format("YYYY-MM-DD")
  );
  return todoStore.getSortedTodos(todos);
});

onMounted(async () => {
  await todoStore.loadTodos();
  await settingsStore.loadSettings();
});

// 选择日期
function selectDate(date: dayjs.Dayjs) {
  selectedDate.value = date;
}

// 上一周
function prevWeek() {
  selectedDate.value = selectedDate.value.subtract(7, "day");
}

// 下一周
function nextWeek() {
  selectedDate.value = selectedDate.value.add(7, "day");
}

// 回到今天
function goToToday() {
  selectedDate.value = dayjs();
}

// 添加待办
function addTodo() {
  if (newTodoContent.value.trim()) {
    todoStore.addTodo(
      newTodoContent.value.trim(),
      selectedDate.value.format("YYYY-MM-DD")
    );
    newTodoContent.value = "";
  }
}

// 开始编辑
function startEdit(id: string, content: string) {
  editingId.value = id;
  editingContent.value = content;
}

// 保存编辑
function saveEdit() {
  if (editingId.value && editingContent.value.trim()) {
    todoStore.updateTodo(editingId.value, {
      content: editingContent.value.trim(),
    });
  }
  editingId.value = null;
  editingContent.value = "";
}

// 取消编辑
function cancelEdit() {
  editingId.value = null;
  editingContent.value = "";
}

// 切换完成状态
function toggleComplete(id: string) {
  todoStore.toggleComplete(id);
}

// 设置优先级
function setPriority(id: string, priority?: "high" | "medium" | "low") {
  todoStore.setPriority(id, priority);
}

// 循环切换优先级
function cyclePriority(id: string) {
  todoStore.cyclePriority(id);
}

// 获取优先级颜色类名
function getPriorityClass(priority?: string) {
  if (!priority) return "";
  return `priority-${priority}`;
}
</script>

<template>
  <div class="main-view">
    <!-- 顶部工具栏 -->
    <ViewToolbar title="待办便签" view-mode="list" @go-to-today="goToToday" />

    <!-- 日期选择栏 -->
    <div class="date-selector">
      <button @click="prevWeek" class="nav-btn">
        <svg
          xmlns="http://www.w3.org/2000/svg"
          width="20"
          height="20"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="2"
          stroke-linecap="round"
          stroke-linejoin="round"
        >
          <polyline points="15 18 9 12 15 6"></polyline>
        </svg>
      </button>

      <div class="week-dates">
        <button
          v-for="day in weekDates"
          :key="day.date.format('YYYY-MM-DD')"
          @click="selectDate(day.date)"
          class="date-item"
          :class="{
            selected: day.isSelected,
            today: day.isToday,
          }"
        >
          <div class="day-name" :class="{ 'today-name': day.isToday }">
            {{ day.dayName }}
          </div>
          <div class="date-str" :class="{ 'today-date': day.isToday }">
            {{ day.dateStr }}
          </div>
          <div v-if="day.isToday" class="today-indicator"></div>
        </button>
      </div>

      <button @click="nextWeek" class="nav-btn">
        <svg
          xmlns="http://www.w3.org/2000/svg"
          width="20"
          height="20"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="2"
          stroke-linecap="round"
          stroke-linejoin="round"
        >
          <polyline points="9 18 15 12 9 6"></polyline>
        </svg>
      </button>
    </div>

    <!-- 待办列表 -->
    <div class="todo-container">
      <div class="todo-list" ref="todoListRef">
        <div v-if="currentTodos.length === 0" class="empty-state">
          <svg
            xmlns="http://www.w3.org/2000/svg"
            width="48"
            height="48"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="1.5"
            stroke-linecap="round"
            stroke-linejoin="round"
          >
            <path d="M9 11l3 3L22 4"></path>
            <path
              d="M21 12v7a2 2 0 01-2 2H5a2 2 0 01-2-2V5a2 2 0 012-2h11"
            ></path>
          </svg>
          <p>暂无待办事项</p>
        </div>

        <div
          v-for="todo in currentTodos"
          :key="todo.id"
          class="todo-item"
          @mouseenter="hoveredId = todo.id"
          @mouseleave="hoveredId = null"
        >
          <!-- 优先级色条 -->
          <div
            class="priority-bar"
            :class="getPriorityClass(todo.priority)"
            @click.stop="cyclePriority(todo.id)"
            title="点击切换优先级"
          ></div>

          <input
            type="checkbox"
            :checked="todo.completed"
            @change="toggleComplete(todo.id)"
            class="checkbox"
          />

          <div
            v-if="editingId !== todo.id"
            @click="startEdit(todo.id, todo.content)"
            class="todo-content"
            :class="{ completed: todo.completed }"
          >
            {{ todo.content }}
          </div>

          <AutoResizeTextarea
            v-else
            v-model="editingContent"
            class="todo-input"
            :autofocus="true"
            @enter="saveEdit"
            @blur="saveEdit"
            @esc="cancelEdit"
          />

          <!-- 优先级选择器 -->
          <div
            class="priority-selector"
            v-show="hoveredId === todo.id && editingId !== todo.id"
          >
            <button
              @click.stop="setPriority(todo.id, 'high')"
              class="priority-btn high"
              :class="{ active: todo.priority === 'high' }"
              title="高优先级"
            >
              <span class="priority-dot"></span>
            </button>
            <button
              @click.stop="setPriority(todo.id, 'medium')"
              class="priority-btn medium"
              :class="{ active: todo.priority === 'medium' }"
              title="中优先级"
            >
              <span class="priority-dot"></span>
            </button>
            <button
              @click.stop="setPriority(todo.id, 'low')"
              class="priority-btn low"
              :class="{ active: todo.priority === 'low' }"
              title="低优先级"
            >
              <span class="priority-dot"></span>
            </button>
            <button
              @click.stop="setPriority(todo.id, undefined)"
              class="priority-btn none"
              :class="{ active: !todo.priority }"
              title="无优先级"
            >
              <span class="priority-dot"></span>
            </button>
          </div>

          <button
            @click.stop="deleteTodo(todo.id)"
            class="delete-btn"
            title="删除"
          >
            <svg
              xmlns="http://www.w3.org/2000/svg"
              width="16"
              height="16"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
            >
              <line x1="18" y1="6" x2="6" y2="18"></line>
              <line x1="6" y1="6" x2="18" y2="18"></line>
            </svg>
          </button>
        </div>
      </div>

      <!-- 添加待办输入框 -->
      <div class="add-todo">
        <AutoResizeTextarea
          v-model="newTodoContent"
          placeholder="添加待办事项..."
          class="add-input"
          @enter="addTodo"
        />
        <button @click="addTodo" class="add-btn">
          <svg
            xmlns="http://www.w3.org/2000/svg"
            width="20"
            height="20"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
          >
            <line x1="12" y1="5" x2="12" y2="19"></line>
            <line x1="5" y1="12" x2="19" y2="12"></line>
          </svg>
        </button>
      </div>
    </div>

    <!-- 删除确认对话框 -->
    <ConfirmDialog
      v-model:show="showDeleteConfirm"
      title="删除待办"
      message="确定要删除这条待办事项吗？此操作无法撤销。"
      confirm-text="删除"
      cancel-text="取消"
      @confirm="confirmDelete"
      @cancel="cancelDelete"
    />
  </div>
</template>

<style scoped>
.main-view {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: var(--bg-primary);
}

.date-selector {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px 20px;
  border-bottom: 1px solid var(--border-color);
  background: var(--bg-secondary);
}

.nav-btn {
  background: none;
  border: none;
  color: var(--text-primary);
  cursor: pointer;
  padding: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  transition: background 0.2s;
  flex-shrink: 0;
}

.nav-btn:hover {
  background: var(--bg-primary);
}

.week-dates {
  display: flex;
  gap: 8px;
  flex: 1;
  overflow-x: auto;
  scrollbar-width: none;
}

.week-dates::-webkit-scrollbar {
  display: none;
}

.date-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 12px 16px;
  background: var(--bg-primary);
  border: 2px solid transparent;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.2s;
  position: relative;
  min-width: 80px;
}

.date-item:hover {
  background: var(--border-color);
}

.date-item.selected {
  background: var(--text-primary);
  color: var(--bg-primary);
}

.date-item.selected .day-name,
.date-item.selected .date-str {
  color: var(--bg-primary);
}

.date-item.today {
  border-color: #22c55e;
}

.day-name {
  font-size: 12px;
  color: var(--text-secondary);
  margin-bottom: 4px;
  font-weight: 500;
}

.day-name.today-name {
  color: #22c55e;
  font-weight: 600;
}

.date-str {
  font-size: 14px;
  color: var(--text-primary);
  font-weight: 600;
}

.date-str.today-date {
  color: #22c55e;
}

.today-indicator {
  position: absolute;
  bottom: 4px;
  width: 6px;
  height: 6px;
  background: #22c55e;
  border-radius: 50%;
}

.todo-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.todo-list {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: var(--text-secondary);
  gap: 12px;
}

.empty-state svg {
  opacity: 0.3;
}

.empty-state p {
  font-size: 14px;
}

.todo-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background: var(--bg-secondary);
  border-radius: 12px;
  position: relative;
}

.todo-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 优先级色条 */
.priority-bar {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 4px;
  border-radius: 12px 0 0 12px;
  cursor: pointer;
  transition: width 0.2s ease;
  z-index: 1;
}

.todo-item:hover .priority-bar {
  width: 6px;
}

.priority-bar.priority-high {
  background: #ef4444;
}

.priority-bar.priority-medium {
  background: #f59e0b;
}

.priority-bar.priority-low {
  background: #3b82f6;
}

/* 优先级选择器 */
.priority-selector {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 6px;
  opacity: 0;
  transition: opacity 0.2s ease;
  margin-right: 8px;
}

.todo-item:hover .priority-selector {
  opacity: 1;
}

.priority-btn {
  width: 18px;
  height: 18px;
  border-radius: 50%;
  border: 2px solid var(--border-color);
  background: var(--bg-primary);
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
}

.priority-btn:hover {
  transform: scale(1.15);
  border-color: var(--text-primary);
}

.priority-btn.active {
  border-width: 3px;
  transform: scale(1.1);
}

.priority-dot {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  display: block;
}

.priority-btn.high .priority-dot {
  background: #ef4444;
}

.priority-btn.medium .priority-dot {
  background: #f59e0b;
}

.priority-btn.low .priority-dot {
  background: #3b82f6;
}

.priority-btn.none .priority-dot {
  background: var(--border-color);
}

.priority-btn.active .priority-dot {
  box-shadow: 0 0 0 2px var(--bg-primary);
}

.checkbox {
  flex-shrink: 0;
  width: 20px;
  height: 20px;
  cursor: pointer;
  accent-color: #22c55e;
}

.todo-content {
  flex: 1;
  font-size: 15px;
  color: var(--text-primary);
  cursor: text;
  padding: 4px 8px;
  border-radius: 6px;
  word-break: break-word;
  line-height: 1.5;
  min-height: 24px;
}

.todo-content:hover {
  background: var(--bg-primary);
}

.todo-content.completed {
  text-decoration: line-through;
  color: var(--text-secondary);
  opacity: 0.6;
}

.todo-input {
  flex: 1;
  font-size: 15px;
  padding: 8px 12px;
  border: 2px solid var(--text-primary);
  border-radius: 8px;
  background: var(--bg-primary);
  color: var(--text-primary);
  outline: none;
}

.delete-btn {
  flex-shrink: 0;
  background: none;
  border: none;
  color: var(--text-secondary);
  cursor: pointer;
  padding: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  opacity: 0;
  transition: all 0.2s;
}

.todo-item:hover .delete-btn {
  opacity: 1;
}

.delete-btn:hover {
  background: #ef4444;
  color: white;
}

.add-todo {
  display: flex;
  gap: 8px;
  padding: 16px 20px;
  border-top: 1px solid var(--border-color);
  background: var(--bg-secondary);
}

.add-input {
  flex: 1;
  font-size: 15px;
  padding: 12px 16px;
  border: 2px solid var(--border-color);
  border-radius: 12px;
  background: var(--bg-primary);
  color: var(--text-primary);
  outline: none;
  transition: border-color 0.2s;
  min-height: 48px;
}

.add-input:focus {
  border-color: var(--text-primary);
}

.add-input::placeholder {
  color: var(--text-secondary);
}

.add-btn {
  flex-shrink: 0;
  width: 48px;
  height: 48px;
  background: var(--text-primary);
  color: var(--bg-primary);
  border: none;
  border-radius: 12px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: opacity 0.2s;
}

.add-btn:hover {
  opacity: 0.8;
}
</style>
